package com.tanhua.sso.service;



import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.sso.mapper.UserMapper;
import com.tanhua.sso.pojo.User;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    /**
     * 用户登录
     *
     * @param phone 手机号
     * @param code  验证码
     * @return
     */
    public String login(String phone, String code) {
        String redisKey = "CHECK_CODE_" + phone;
        boolean isNew = false;

        String redisData = redisTemplate.opsForValue().get(redisKey);
        if (!StringUtils.equals(redisData, code)) {
            log.info("验证码错误~ phone" + phone);
            return null; //验证码错误
        }
        redisTemplate.delete(redisKey);

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", phone);
        User user = userMapper.selectOne(queryWrapper);
        //新用户
        if (user == null) {
            isNew = true;
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            userMapper.insert(user);
        }
        //生成token
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());

        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS256, secret)
                .setExpiration(new DateTime().plusHours(12).toDate())
                .compact();

        try {
            HashMap<String, Object> msg = new HashMap<>();
            msg.put("id", user.getId());
            msg.put("date", System.currentTimeMillis());

            this.rocketMQTemplate.convertAndSend("tanhua-sso-login", msg);
        } catch (MessagingException e) {
            log.error("发送消息失败!", e);
        }

        return token + "|" + isNew;
    }

    public User queryUserByToken(String token) {
        try {
            //通过token解析数据
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();

            User user = new User();
            user.setId(Long.valueOf(body.get("id").toString()));

            String redisKey = "TANHUA_USER_MOBILE_" + user.getId();

            //需要返回user对象中的mobile，需要查询数据库获取到mobile数据
            //如果每次都查询数据库，必然会导致性能问题，需要对用户的手机号进行缓存操作
            //数据缓存时，需要设置过期时间，过期时间要与token的时间一致
            //如果用户修改了手机号，需要同步修改redis中的数据
            if (this.redisTemplate.hasKey(redisKey)) {
                String phone = redisTemplate.opsForValue().get(redisKey);
                user.setMobile(phone);
            } else {
                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("id", user.getId());
                String mobile = userMapper.selectOne(queryWrapper).getMobile();
                user.setMobile(mobile);
                long timeout=Long.parseLong(body.get("exp").toString()) * 1000 - System.currentTimeMillis();
                redisTemplate.opsForValue().set(redisKey, mobile, timeout, TimeUnit.MILLISECONDS);

            }
            return user;
        } catch (ExpiredJwtException e) {
            log.info("token已经过期！token" + token);
        } catch (Exception e) {
            log.error("token不合法！", e);
        }
        return null;
    }
}
